package com.thinkgem.jeesite.androidpn.server.xmpp.handler;

import com.alibaba.druid.util.StringUtils;
import com.thinkgem.jeesite.androidpn.server.model.User;
import com.thinkgem.jeesite.androidpn.server.service.UserNotFoundException;
import com.thinkgem.jeesite.androidpn.server.service.UserService;
import com.thinkgem.jeesite.androidpn.server.xmpp.UnauthorizedException;
import com.thinkgem.jeesite.androidpn.server.xmpp.session.ClientSession;
import com.thinkgem.jeesite.androidpn.server.xmpp.session.Session;
import com.thinkgem.jeesite.common.utils.SpringContextHolder;
import com.thinkgem.jeesite.modules.notify.common.MessageTagOrAliasType;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.service.DictService;
import org.dom4j.Element;
import org.xmpp.packet.IQ;
import org.xmpp.packet.PacketError;

import java.util.Date;
import java.util.List;

/**
 * @Author: hf
 * @Description:
 * @Date: 2018/12/21 14:08
 * @Version: 1.0
 */
public class IQUserAliasOrTagHandler extends IQHandler {

    private static final String NAMESPACE = "androidpn:iq:useraliasortag";

    private UserService userService = SpringContextHolder.getBean(UserService.class);

    private DictService dictService = SpringContextHolder.getBean(DictService.class);

    @Override
    public IQ handleIQ(IQ packet) throws UnauthorizedException {
        ClientSession session = sessionManager.getSession(packet.getFrom());
        IQ reply;
        if (session == null) {
            log.error("Session not found for key " + packet.getFrom());
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.internal_server_error);
            return reply;
        }

        if (session.getStatus() == Session.STATUS_AUTHENTICATED) {

            if (IQ.Type.set.equals(packet.getType())) {
                Element element = packet.getChildElement();

                String username = element.elementText("username");
                String alias = element.elementText("alias");
                String tag = element.elementText("tag");
                String appid = element.elementText("appid");
                User user;
                if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(appid)) {
                    try {
                        user = userService.getUserByUsernameAndAppId(username, appid);
                        if (user != null && (!StringUtils.isEmpty(alias) || !StringUtils.isEmpty(tag))) {
                            user.setAlias(alias);
                            user.setTag(tag);
                            userService.updateUser(user);
                            if (!StringUtils.isEmpty(alias)) {
                                List<String> pushMessageTagOrAlias = dictService.getPushMessageTagOrAlias(MessageTagOrAliasType.USER_ALIAS.getCode(), alias);
                                if (pushMessageTagOrAlias.size() <= 0) {
                                    Dict dict = this.getDict(tag);
                                    dict.setLabel("推送消息用户别名");
                                    dict.setType(MessageTagOrAliasType.USER_ALIAS.getCode());
                                    dict.setDescription("推送消息用户别名:" + alias);
                                    dictService.save(dict);
                                }
                            }
                            if (!StringUtils.isEmpty(tag)) {
                                List<String> pushMessageTagOrAlias = dictService.getPushMessageTagOrAlias(MessageTagOrAliasType.USER_TAG.getCode(), tag);
                                if (pushMessageTagOrAlias.size() <= 0) {
                                    Dict dict = this.getDict(tag);
                                    dict.setLabel("推送消息用户标签");
                                    dict.setType(MessageTagOrAliasType.USER_TAG.getCode());
                                    dict.setDescription("推送消息用户别名:" + tag);
                                    dictService.save(dict);
                                }
                            }
                        }
                    } catch (UserNotFoundException e) {
                        e.printStackTrace();
                    }

                }
            }
        }

        return null;
    }

    @Override
    public String getNamespace() {
        return NAMESPACE;
    }


    public Dict getDict(String aliasOrTag) {
        Dict dict = new Dict();
        dict.setValue(aliasOrTag);
        dict.setCreateDate(new Date());
        dict.setUpdateDate(new Date());
        dict.setSort(10);
        return dict;
    }
}
